package com.cjc.controller;

import com.cjc.common.utils.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.ResponseEntity;

import java.io.File;
import java.util.*;

/**
 * @Author: 陈江灿
 * @CreateTime: 2025-01-21
 */
@RestController
@RequestMapping("/photos")
public class PhotoController {

    @Value("${app.save-path}")
    private String savePath;

    @GetMapping("/list")
    public R list(@RequestParam(defaultValue = "1") int page,
                  @RequestParam(defaultValue = "10") int pageSize) {
        File directory = new File(savePath);
        if (!directory.exists() || !directory.isDirectory()) {
            throw new IllegalArgumentException("目录不存在或不是有效目录: " + savePath);
        }
        File[] files = directory.listFiles((dir, name) ->
                name.toLowerCase().endsWith(".jpg") || name.toLowerCase().endsWith(".png"));

        if (files == null || files.length == 0) {
            return R.ok(ResponseEntity.ok(Collections.emptyMap()));
        }

        // 对文件按最后修改时间排序（从新到旧）
        Arrays.sort(files, (f1, f2) -> Long.compare(f2.lastModified(), f1.lastModified()));

        // 计算分页的起始和结束索引
        int startIndex = (page - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, files.length);

        // 获取当前页的文件列表
        List<String> photoNames = new ArrayList<>();
        for (int i = startIndex; i < endIndex; i++) {
            photoNames.add(files[i].getName());
        }

        // 计算总页数
        int totalPages = (int) Math.ceil((double) files.length / pageSize);

        // 返回分页数据
        Map<String, Object> response = new HashMap<>();
        response.put("photos", photoNames);
        response.put("currentPage", page);
        response.put("totalPages", totalPages);

        return R.ok(ResponseEntity.ok(response));
    }
}
